global with sharing class globalInstagramPost {
    
    
     public static Datetime convertUnixDateTime(String unixDate){
        Integer unixTime = integer.valueOf(unixDate);
        DateTime dateInstance = datetime.newInstanceGmt(1970, 1, 1, 0, 0, 0);
        String dateTimeValue = dateInstance.addSeconds(unixTime).format();
        Datetime dt = DateTime.parse(dateTimeValue);
        return dt;
    }
    
 //Retreive latest media   
    public static String getInfoMediaService(String user) {
          String user_id;
        
            Instagram_Token__c token = [SELECT Access_Token__c, User_Id__c FROM Instagram_Token__c LIMIT 1]; 
            //hardcode values for POC Instagram button leads
            String access_token = token.Access_Token__c;
            if(user == null) { //munchbakery
                user_id = token.User_Id__c;
            } else { //munchmaleh   
                user_id = user; 
            } 
        
        
        string url = 'https://api.instagram.com/v1/users/' + user_id + '/media/recent/?count=33&access_token=' + access_token;

        HttpRequest req = new HttpRequest();
        req.setEndpoint(url);
        req.setMethod('GET');
        Http h = new Http();
        HttpResponse res = h.send(req);
        String userData = res.getBody();   
        return userData; 
    }   
   //used for comment test class
   public static String getCommentService(String media, String access_token) {
                string url = 'https://api.instagram.com/v1/media/' + media + '/comments?&access_token=' + access_token;
                HttpRequest req = new HttpRequest();
                req.setEndpoint(url);
                req.setMethod('GET');
                Http h = new Http();
                HttpResponse res = h.send(req);
                String userData = res.getBody(); 
                return userData;  
   } 

   //used for likes test class
   public static String getLikeService(String media, String access_token) {
                string url = 'https://api.instagram.com/v1/media/' + media + '/likes?&access_token=' + access_token;
                HttpRequest req = new HttpRequest();
                req.setEndpoint(url);
                req.setMethod('GET');
                Http h = new Http();
                HttpResponse res = h.send(req);
                String userData = res.getBody(); 
                return userData;  
   }    
   

//Retreive latest media
@future(callout=true)
webservice static void retreiveUserMediaInfo() {  // Get Media Info
        List<RecordType> recordType = [SELECT Id,DeveloperName,Name,IsActive,SObjectType from RecordType where IsActive =: true AND SObjectType =: 'Instagram_Conversation__c' and Name = 'MunchBakery Post'];
        List<Instagram_Conversation__c> instaList = new List<Instagram_Conversation__c>();
        
        //not working on prod, callout not supported on scheduled apex error
        //String user;         
        //string userDataBakery = globalInstagramPost.getInfoMediaService(user);


            String user_id;
        
            Instagram_Token__c token = [SELECT Access_Token__c, User_Id__c FROM Instagram_Token__c LIMIT 1]; 
            //hardcode values for POC Instagram button leads
            String access_token = token.Access_Token__c;
            user_id = token.User_Id__c;
        
        
            string url = 'https://api.instagram.com/v1/users/' + user_id + '/media/recent/?count=33&access_token=' + access_token;
    
            HttpRequest req = new HttpRequest();
            req.setEndpoint(url);
            req.setMethod('GET');
            Http h = new Http();
            HttpResponse res = h.send(req);
            String userDataBakery = res.getBody();
            //PO 01262014    


        JSONMedia obj = JSONMedia.parse(userDataBakery);

        if(obj != null) {
            for(integer i=0; obj.data.size() > i; i++) {
                 Instagram_Conversation__c insta = new Instagram_Conversation__c();
                 insta.Recordtypeid = recordType[0].Id; // MunchBakery Post
                 insta.Published_Date__c = convertUnixDateTime(obj.data[i].created_time);  
                if(obj.data[i].caption != null){        
                    insta.Caption_Text__c = obj.data[i].caption.text;
                }
                insta.Media_ID__c = obj.data[i].id;
                insta.Instagram_Picture__c = obj.data[i].images.thumbnail.url;
                insta.Author_Full_Name__c =  obj.data[i].user.full_name;
                insta.Author_Username__c =  obj.data[i].user.username;
                insta.Profile_Picture__c = obj.data[i].user.profile_picture;
                insta.Instagram_ID__c = obj.data[i].user.id; 
                insta.Comment_Count__c = obj.data[i].comments.count;
                insta.Likes_Count__c = obj.data[i].likes.count;
                //insta.Tags__c = obj.data[i].tags[0].tag;
                insta.OwnerId = '005b0000000EXPL';
                //string link = ;
                insta.Instagram_Link__c = obj.data[i].link;
                instaList.add(insta);
            }
        }
        
        
        //Munchmaleh
            String user = '367906135'; //munchmaleh
            
            string urlMaleh = 'https://api.instagram.com/v1/users/' + user + '/media/recent/?count=33&access_token=' + access_token;
    
            HttpRequest reqMaleh = new HttpRequest();
            reqMaleh.setEndpoint(urlMaleh);
            reqMaleh.setMethod('GET');
            Http hMaleh = new Http();
            HttpResponse resMaleh = hMaleh.send(reqMaleh);
            String userData1 = resMaleh.getBody();
            JSONMedia obj1 = JSONMedia.parse(userData1);
            system.debug('object1 =>' + obj1);
    
            if(obj1 != null) {
                for(integer i=0; obj1.data.size() > i; i++) {
                     Instagram_Conversation__c insta1 = new Instagram_Conversation__c();
                     insta1.Recordtypeid = recordType[0].Id; // MunchBakery Post
                     insta1.Published_Date__c = convertUnixDateTime(obj1.data[i].created_time);  
                    if(obj1.data[i].caption != null){  
                        insta1.Caption_Text__c = obj1.data[i].caption.text;
                    }
                    insta1.Media_ID__c = obj1.data[i].id;
                    insta1.Instagram_Picture__c = obj1.data[i].images.thumbnail.url;
                    insta1.Author_Full_Name__c =  obj1.data[i].user.full_name;
                    insta1.Author_Username__c =  obj1.data[i].user.username;
                    insta1.Profile_Picture__c = obj1.data[i].user.profile_picture;
                    insta1.Instagram_ID__c = obj1.data[i].user.id; 
                    insta1.Comment_Count__c = obj1.data[i].comments.count;
                    insta1.Likes_Count__c = obj1.data[i].likes.count;
					//insta1.Tags__c = obj1.data[i].tags[0].tag;                    
                    insta1.OwnerId = '005b0000000EXPL';
                    //string link = ;
                    insta1.Instagram_Link__c = obj1.data[i].link;
                    instaList.add(insta1);
                }
            }
            
        
        
        
        
        
        
        try
        {
		Schema.SObjectField f = Instagram_Conversation__c.Fields.Media_ID__c;
        Database.upsertResult[] dsr = Database.upsert(instaList, f, false);        	
        system.debug('inserted list =>' + dsr);	
         //Database.saveResult[] dsr = Database.insert(instaList, false);
         //insert instaList;
        } 
        catch(Exception e)
        {
            system.debug('Media Already Exist!');
        }


    }    





//Retreive comments from existing media
 webservice static void postSchedCommentServiceRequest(String instaRecord, String access_token) {
        //get record type
        List<RecordType> recordType = [SELECT Id,DeveloperName,Name,IsActive,SObjectType from RecordType where IsActive =: true AND SObjectType =: 'Instagram_Conversation__c' and Name = 'IG User Post'];
        
        //get media record
        Instagram_Conversation__c instaMedia = [Select Id, Media_id__c From Instagram_Conversation__c where Media_id__c=:instaRecord];
        
        string userData;
        string existingMedia;       
       
       List<Instagram_Conversation__c> instaUpdateList = new List<Instagram_Conversation__c>();
       List<Instagram_Conversation__c> commentsList = new List<Instagram_Conversation__c>();
                //get username Endpoint
                //string url = 'https://api.instagram.com/v1/media/' + instaRecord.media_id__c + '/comments?&access_token=' + access_token; 
                //Instantiate a new http object
                //get username Endpoint
                string url = 'https://api.instagram.com/v1/media/' + instaMedia.Media_id__c + '/comments?&access_token=' + access_token;
                HttpRequest req = new HttpRequest();
                req.setEndpoint(url);
                req.setMethod('GET');
                Http h = new Http();
                HttpResponse res = h.send(req);
                userData = res.getBody();   
                
                userData = userData.replace('"from":', '"from_user":');
                JSONMediaComments obj = JSONMediaComments.parse(userData);
                System.assert(obj != null);
                //system.debug('my obj =>' + obj);
				if(obj.data != null) {
	                for(integer i=0; obj.data.size() > i; i++) {
	                    Instagram_Conversation__c insta = new Instagram_Conversation__c();
	                    insta.Created_Time__c = convertUnixDateTime(obj.data[i].created_time);
	                    //hardcoded record type
	                    insta.Recordtypeid = recordType[0].id; //IG User Post
	                    //system.debug('insta comments loop =>' + obj);
	                    insta.Author_Full_Name__c =  obj.data[i].from_user.full_name;
	                    insta.Author_Username__c =  obj.data[i].from_user.username;
	                    insta.Profile_Picture__c = obj.data[i].from_user.profile_picture;
						//comments does not have bio on json                   
	                    insta.Instagram_ID__c = obj.data[i].from_user.id;  
	                    insta.Comment_ID__c =   obj.data[i].id;                 
	                    insta.Message__c = obj.data[i].text;  
	                    insta.Parent__c =   instaMedia.id;
	                    insta.Type__c = 'Comment';
	                    insta.OwnerId = '005b0000000EXPL';                
	                    commentsList.add(insta); 
	                
	                } // end for comment loop
				}
                datetime dateinAdvance = datetime.now();
                instaMedia.Next_API_Callout_Datetime__c = dateinAdvance.addMinutes(15);
                instaUpdateList.add(instaMedia);
            
            
            try
            {
            system.debug('comments list inserted ' + commentsList.size());
            system.debug('comments to insert ' + commentsList);
             Database.saveResult[] dsr = Database.insert(commentsList, false);
             //update media post with latest id
             update instaUpdateList;
             system.debug('records inserted');
            } 
            catch(Exception e)
            {
                 system.debug('failed =>' + e);
            }

    }    
        
//Retreive comments from existing media
 webservice static void postSchedLikeServiceRequest(String instaRecord, String access_token) {
        //get record type
        List<RecordType> recordType = [SELECT Id,DeveloperName,Name,IsActive,SObjectType from RecordType where IsActive =: true AND SObjectType =: 'Instagram_Conversation__c' and Name = 'IG User Post'];
        
        //get media record
        Instagram_Conversation__c instaMedia = [Select Id, Media_id__c From Instagram_Conversation__c where Media_id__c=:instaRecord];
        
        string userData;
        string existingMedia;       
       
       List<Instagram_Conversation__c> instaUpdateList = new List<Instagram_Conversation__c>();
       List<Instagram_Conversation__c> likesList = new List<Instagram_Conversation__c>();
                //get username Endpoint
                //string url = 'https://api.instagram.com/v1/media/' + instaRecord.media_id__c + '/comments?&access_token=' + access_token; 
                //Instantiate a new http object
                //get username Endpoint
                string url = 'https://api.instagram.com/v1/media/' + instaMedia.Media_id__c + '/likes?&access_token=' + access_token;
                HttpRequest req = new HttpRequest();
                req.setEndpoint(url);
                req.setMethod('GET');
                Http h = new Http();
                HttpResponse res = h.send(req);
                userData = res.getBody();   
                
                JSONMediaLikes obj = JSONMediaLikes.parse(userData);
                System.assert(obj != null);
                //system.debug('my obj =>' + obj); 
                if(obj.data != null) {
	                for(integer i=0; obj.data.size() > i; i++) {
	                    Instagram_Conversation__c insta = new Instagram_Conversation__c();
	                    insta.Recordtypeid = recordType[0].id; //IG User Post
	                    insta.Author_Full_Name__c =  obj.data[i].full_name;
	                    insta.Author_Username__c =  obj.data[i].username;
	                    insta.Profile_Picture__c = obj.data[i].profile_picture;
	                    insta.Author_s_Bio__c = obj.data[i].bio;
	                    insta.Instagram_ID__c = obj.data[i].id;  
	                    insta.Like_ID__c =   obj.data[i].id;
	                    insta.Parent__c =   instaMedia.id;
	                    insta.Type__c = 'Like';
	                    insta.OwnerId = '005b0000000EXPL';                
	                    likesList.add(insta); 
	                
	                } // end for like loop
                }
                datetime dateinAdvance = datetime.now();
                instaMedia.Next_API_Callout_Datetime__c = dateinAdvance.addMinutes(15);
                instaUpdateList.add(instaMedia);
            
            
            try
            {
				system.debug('likes list inserted ' + likesList.size());
	            system.debug('likes to insert ' + likesList);
	            //Schema.SObjectField f = Instagram_Conversation__c.Fields.Like_ID__c;
	            Database.saveResult[] dsr = Database.insert(likesList, false);
	            //update media post with latest id
	            update instaUpdateList;
             	system.debug('records inserted');
            } 
           		catch(Exception e)
            {
                system.debug('failed =>' + e);
            }

    }        
         
    /* Working Commented out due to Schedulable does not work with callout if not future 
    Usage: 
    //Media Retreive
    string res = globalInstagramPost.getInfoMediaService();
    globalInstagramPost.retreiveUserMediaInfo(res);
    
    or
    //Comments Retrieve
    Map<string, string> httpMediaMap = globalInstagramPost.createMediaCommentService(); 
    globalInstagramPost.postSchedCommentServiceRequest(httpMediaMap);   
    
    
    public static String getInfoMediaService() {
        Instagram_Token__c token = [SELECT Access_Token__c, User_Id__c FROM Instagram_Token__c LIMIT 1]; 
        //hardcode values for POC Instagram button leads
        String access_token = token.Access_Token__c;
        String user_id = token.User_Id__c;
        
        string url = 'https://api.instagram.com/v1/users/' + user_id + '/media/recent/?count=33&access_token=' + access_token;

        HttpRequest req = new HttpRequest();
        req.setEndpoint(url);
        req.setMethod('GET');
        Http h = new Http();
        HttpResponse res = h.send(req);
        String userData = res.getBody();   
        return userData;
    }  
    

    public static Map<String,String> createMediaCommentService() {
        
        
        datetime dt = datetime.now();
        List<Instagram_Conversation__c> instaList = [Select Id, Media_Id__c From Instagram_Conversation__c where Media_Id__c != null and (Next_API_Callout_Datetime__c = null OR Next_API_Callout_Datetime__c < :dt) LIMIT 10];   
                
        Instagram_Token__c token = [SELECT Access_Token__c, Client_Id__c, User_Id__c FROM Instagram_Token__c LIMIT 1]; 
        //hardcode values for POC Instagram button leads
        string access_token = token.Access_Token__c;
        string client_id = token.Client_Id__c; 
        string userData;
        string existingMedia;
        Map<string, string> httpMediaMap = new Map<String, String>();
        
        for(Instagram_Conversation__c instaRecord : instaList) {
                //get username Endpoint
                string url = 'https://api.instagram.com/v1/media/' + instaRecord.media_id__c + '/comments?&access_token=' + access_token;
                HttpRequest req = new HttpRequest();
                req.setEndpoint(url);
                req.setMethod('GET');
                Http h = new Http();
                HttpResponse res = h.send(req);
                userData = res.getBody();   
                httpMediaMap.put(instaRecord.media_id__c, userData);
                
        }
        

        return httpMediaMap;
    }   

           
    
  public static void retreiveUserMediaInfo(String userData) {  // Get Media Info
        List<RecordType> recordType = [SELECT Id,DeveloperName,Name,IsActive,SObjectType from RecordType where IsActive =: true AND SObjectType =: 'Instagram_Conversation__c' and Name = 'MunchBakery Post'];
        system.debug('retrieveuserData =>' + userData);
        JSONMedia obj = JSONMedia.parse(userData);
        //System.assert(obj != null);
        //system.debug('my obj =>' + obj);  
        //ssystem.debug('paginate =>' + obj.pagination);
        //system.debug('size =>' + obj.data.size());
        List<Instagram_Conversation__c> instaList = new List<Instagram_Conversation__c>();
        if(obj != null) {
            for(integer i=0; obj.data.size() > i; i++) {
                 Instagram_Conversation__c insta = new Instagram_Conversation__c();
                 insta.Recordtypeid = recordType[0].Id; // MunchBakery Post
                 insta.Published_Date__c = convertUnixDateTime(obj.data[i].created_time);  
                if(obj.data[i].caption != null){        
                    insta.Caption_Text__c = obj.data[i].caption.text;
                }
                insta.Media_ID__c = obj.data[i].id;
                insta.Instagram_Picture__c = obj.data[i].images.thumbnail.url;
                insta.Author_Full_Name__c =  obj.data[i].user.full_name;
                insta.Author_Username__c =  obj.data[i].user.username;
                insta.Profile_Picture__c = obj.data[i].user.profile_picture;
                insta.Instagram_ID__c = obj.data[i].user.id; 
                insta.Comment_Count__c = obj.data[i].comments.count;
                insta.OwnerId = '005b0000000EXPL';
                //string link = ;
                insta.Instagram_Link__c = obj.data[i].link;
                instaList.add(insta);
            }
        }
        
        
        try
        {
         Database.saveResult[] dsr = Database.insert(instaList, false);
         //insert instaList;
        } 
        catch(Exception e)
        {
            system.debug('Media Already Exist!');
        }


    }    
 
 public static void postSchedCommentServiceRequest(Map<string, string> httpMediaMap) {
        List<RecordType> recordType = [SELECT Id,DeveloperName,Name,IsActive,SObjectType from RecordType where IsActive =: true AND SObjectType =: 'Instagram_Conversation__c' and Name = 'IG User Post'];
      
        datetime dt = datetime.now();
        //638128005141953183_251993517
        List<Instagram_Conversation__c> instaList = [Select Id, Media_Id__c From Instagram_Conversation__c where Media_Id__c != null and (Next_API_Callout_Datetime__c = null OR Next_API_Callout_Datetime__c < :dt) ORDER By CreatedDate ASC LIMIT 10];   
        string userData;
        string existingMedia;
       
       List<Instagram_Conversation__c> instaUpdateList = new List<Instagram_Conversation__c>();
       List<Instagram_Conversation__c> commentsList = new List<Instagram_Conversation__c>();
       for(Instagram_Conversation__c instaRecord : instaList) {
                //get username Endpoint
                //string url = 'https://api.instagram.com/v1/media/' + instaRecord.media_id__c + '/comments?&access_token=' + access_token; 
                //Instantiate a new http object
                userData = httpMediaMap.get(instaRecord.media_id__c);
                userData = userData.replace('"from":', '"from_user":');
                JSONMediaComments obj = JSONMediaComments.parse(userData);
                System.assert(obj != null);
                //system.debug('my obj =>' + obj); 
                for(integer i=0; obj.data.size() > i; i++) {
                    Instagram_Conversation__c insta = new Instagram_Conversation__c();
                    insta.Created_Time__c = convertUnixDateTime(obj.data[i].created_time);
                    //hardcoded record type
                    insta.Recordtypeid = recordType[0].id; //IG User Post
                    //system.debug('insta comments loop =>' + obj);
                    insta.Author_Full_Name__c =  obj.data[i].from_user.full_name;
                    insta.Author_Username__c =  obj.data[i].from_user.username;
                    insta.Profile_Picture__c = obj.data[i].from_user.profile_picture;
                    insta.Instagram_ID__c = obj.data[i].from_user.id;  
                    insta.Comment_ID__c =   obj.data[i].id;
                    insta.Message__c = obj.data[i].text;  
                    insta.Parent__c =   instaRecord.id;
                    insta.Type__c = 'Comment';
                    insta.OwnerId = '005b0000000EXPL';                
                    commentsList.add(insta); 
                
                } // end for comment loop
                datetime dateinAdvance = datetime.now();
                instaRecord.Next_API_Callout_Datetime__c = dateinAdvance.addHours(2);
                instaUpdateList.add(instaRecord);
            } // end for insta loop
            
            
            try
            {
            system.debug('comments list inserted ' + commentsList.size());
            system.debug('comments to insert ' + commentsList);
             Database.saveResult[] dsr = Database.insert(commentsList, false);
             //update media post with latest id
             update instaUpdateList;
             system.debug('records inserted');
             //insert instaList;
            } 
            catch(Exception e)
            {
                 system.debug('failed =>' + e);
            }

    }    
    */

    
}